import Constants from "../libs/Constants";
import GameData from "../libs/GameData";
import { GameEvent } from "../libs/GameEvent";
import Helper from "../libs/HelperMgr";

const {ccclass, property} = cc._decorator;

@ccclass
export default class UILevel extends cc.Component {

    @property(cc.Node)
    levels: cc.Node = null;


    onLoad () {}

    onEnable() {
        GameEvent.on(Constants.StageEvent.RefreshLevel,this.refreshLevelList,this);
    }

    start () {
        if(GameData.instance.gameMaxStage < GameData.instance.gameStage){
            GameData.instance.gameMaxStage = GameData.instance.gameStage;
        }
        this.refreshLevelList();

    }

    refreshLevelList(){
        for (let i = 0; i < this.levels.childrenCount; i++) {
            let select = this.levels.children[i].getChildByName("select")
            select.active = GameData.instance.gameStage == i+1;
            let level = this.levels.children[i].getChildByName("level");
            level.getComponent(cc.Label).string = (i+1).toString();
            level.color = i < GameData.instance.gameMaxStage ? cc.Color.BLUE : cc.Color.GRAY;
            let unlock = this.levels.children[i].getChildByName("unlock")
            unlock.active = i < GameData.instance.gameMaxStage;
            let locked = this.levels.children[i].getChildByName("locked")
            locked.active = i >= GameData.instance.gameMaxStage; 
        }
    }

    onLevel(event, customEventData){
        let index = parseInt(customEventData);
        if(index == GameData.instance.gameMaxStage+1){
            Helper.showUI(Constants.UIName.UIUnlockLevel);
        }else if(index <=  GameData.instance.gameMaxStage){
            GameData.instance.gameStage = index;
        }
        this.refreshLevelList();
    }



    onClose(){
        this.node.removeFromParent();
        this.node.destroy();
    }


    onDisable(){
        GameEvent.off(Constants.StageEvent.RefreshLevel,this.refreshLevelList,this);
    }
}
